package org.dromara.common.encrypt.config;

import com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.encrypt.core.EncryptorManager;
import org.dromara.common.encrypt.interceptor.MybatisDecryptInterceptor;
import org.dromara.common.encrypt.interceptor.MybatisEncryptInterceptor;
import org.dromara.common.encrypt.properties.EncryptorProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;


/**
 * @Author 刘武贵
 * @Date 2024/8/15 22:00
 * @Description 功能描述：加解密配置
 */
@AutoConfiguration(after = MybatisPlusAutoConfiguration.class)
// 启用EncryptorProperties配置属性
@EnableConfigurationProperties(EncryptorProperties.class)
// 当mybatis-encryptor的启用配置为true时，该配置类才会被加载
@ConditionalOnProperty(value = "mybatis-encryptor.enable", havingValue = "true")
@Slf4j
public class EncryptorAutoConfiguration {

    /**
     * 加解密属性配置类
     */
    @Autowired
    private EncryptorProperties properties;

    /**
     * 配置EncryptorManager Bean
     * EncryptorManager负责管理加密器，根据类型别名包扫描配置生成
     *
     * @param mybatisPlusProperties MybatisPlus属性配置，包含类型别名包等信息
     * @return EncryptorManager实例，用于管理和获取加密器
     */
    @Bean
    public EncryptorManager encryptorManager(MybatisPlusProperties mybatisPlusProperties) {
        return new EncryptorManager(mybatisPlusProperties.getTypeAliasesPackage());
    }

    /**
     * 配置MybatisEncryptInterceptor Bean
     * MybatisEncryptInterceptor是一个拦截器，用于在数据写入数据库前进行加密
     *
     * @param encryptorManager EncryptorManager实例，提供加密器管理
     * @return MybatisEncryptInterceptor实例，用于加密数据
     */
    @Bean
    public MybatisEncryptInterceptor mybatisEncryptInterceptor(EncryptorManager encryptorManager) {
        return new MybatisEncryptInterceptor(encryptorManager, properties);
    }

    /**
     * 配置MybatisDecryptInterceptor Bean
     * MybatisDecryptInterceptor是一个拦截器，用于在从数据库读取数据后进行解密
     *
     * @param encryptorManager EncryptorManager实例，提供加密器管理
     * @return MybatisDecryptInterceptor实例，用于解密数据
     */
    @Bean
    public MybatisDecryptInterceptor mybatisDecryptInterceptor(EncryptorManager encryptorManager) {
        return new MybatisDecryptInterceptor(encryptorManager, properties);
    }

}



